package com.libre.controller;

import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;

import javax.print.PrintService;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.Orientation;
import org.apache.pdfbox.printing.PDFPageable;

/**
 *
 * pdfbox 只支持PDF
 *
 *
 */
public class PdfBox {
    public static void main(String[] args)throws Exception {
        printCnzz();
    }

    public static void printCnzz(){
        PDDocument document = null;
        try {
            System.out.println("print");
            String pdfFile = "C:\\Users\\DELL\\Desktop\\绩效分配需求.pdf";//文件

            String printerName = "Samsung M2070 Series";//打印机名包含字串

            document = PDDocument.load(new File(pdfFile));


            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(new File(pdfFile).getName());

            if (printerName != null) {
                PrintService[] printService = PrinterJob.lookupPrintServices();//获得本台电脑连接的所有打印机
                for (int i = 0; i < printService.length; i++) {
                    System.out.println(printService[i].getName());
                    if (printService[i].getName().contains(printerName)) {
                        System.out.println();
                        System.out.println(printService[i].getName() + "--------------------------------------");
                        System.out.println();
                        printJob.setPrintService(printService[i]);
                        break;
                    }
                }
            }
            printJob.setPageable(new PDFPageable(document, Orientation.AUTO,
                    false, 0));

            printJob.print();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}